package com.tiza.xiaoyoubao.ui.fragment;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.orhanobut.hawk.Hawk;
import com.tianze.library.adapter.recycler.RecyclerBaseAdapter;
import com.tianze.library.base.BaseStoreHouseRefreshRecyclerFragment;
import com.tianze.library.view.EmptyLayout;
import com.tiza.xiaoyoubao.R;
import com.tiza.xiaoyoubao.app.Constants;
import com.tiza.xiaoyoubao.app.UIHelper;
import com.tiza.xiaoyoubao.entity.MpJDTaskOrderInfo;
import com.tiza.xiaoyoubao.entity.UserInfo;
import com.tiza.xiaoyoubao.net.ApiHttpClient;
import com.tiza.xiaoyoubao.net.JsonCallback;
import com.tiza.xiaoyoubao.net.ResponseInfo;
import com.tiza.xiaoyoubao.utils.DateUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Request;

/**
 * Created by mapple on 17/4/10.
 * 手机京东任务
 */

public class MpJDTaskFragment extends BaseStoreHouseRefreshRecyclerFragment {


    UserInfo userInfo = Hawk.get(Constants.KEY_USER_INFO, (UserInfo) null);
    private List<MpJDTaskOrderInfo> infoList;


    private List<MpJDTaskOrderInfo> mList = new ArrayList<>();

    private List<MpJDTaskOrderInfo> mList1 = new ArrayList<>();

    private static int Year, Month, Day, Hour, Minute;
    private static SimpleDateFormat df;
    //时间差
    private static long minute;

    private static long subTime(String time) {
        time = time.replaceAll(" ", "-").replaceAll(":", "-");
        String TaskTime[] = time.split("-");
        Year = Integer.parseInt(TaskTime[0]);
        Month = Integer.parseInt(TaskTime[1]) - 1;
        Day = Integer.parseInt(TaskTime[2]);
        Hour = Integer.parseInt(TaskTime[3]);
        Minute = Integer.parseInt(TaskTime[4]);
        Calendar Time = Calendar.getInstance();
        Time.set(Year, Month, Day, Hour, Minute);//任务时间
        long timeSystem = Time.getTimeInMillis();
        return timeSystem;
    }

    /**
     * 时间比较
     * taskTime 任务时间
     * systemTime 系统时间
     */

    private static long timeCompare(String taskTime, String systemTime) {
        minute = (subTime(taskTime) - subTime(systemTime)) / (1000 * 60);
        return minute;
    }

    @Override
    protected RecyclerBaseAdapter getListAdapter() {
        return new TaskListAdapter();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        pageSize = Integer.MAX_VALUE;
        selectOver();
        df = new SimpleDateFormat("yyyy-MM-dd HH:mm");//设置日期格
    }

    @Override
    protected void onItemClick(View view, int position) {
        super.onItemClick(view, position);
        MpJDTaskOrderInfo info = (MpJDTaskOrderInfo) mAdapter.getData().get(position);
        Hawk.put(Constants.KEY_MPJDTASKOEDER_INFO,info);
        Bundle args = new Bundle();
        args.putSerializable("info", info);

        if (info.getSettingTime().equals("1") && (timeCompare(
                DateUtils.getDateToString(info.getStartHour().substring(0, info.getStartHour()
                                                                               .length() - 3)),
                df.format(new Date())) > 0)) {
            toast("任务时间还未到,请稍后再接");
        } else {
            UIHelper.showMpJDTaskDetial(mActivity, args);
            finish();
        }

    }

    public static class TaskListAdapter extends RecyclerBaseAdapter {

        @Override
        protected View onCreateItemView(ViewGroup parent, int viewType) {
            return getLayoutInflater(parent.getContext()).inflate(R.layout.item_mp_jingdong_task,
                                                                  parent, false
            );
        }

        @Override
        protected ViewHolder onCreateItemViewHolder(View view, int viewType) {
            return new ViewHolder(viewType, view);
        }

        @Override
        public void onBindItemViewHolder(RecyclerBaseAdapter.ViewHolder holder, int position) {
            super.onBindItemViewHolder(holder, position);
            final ViewHolder vh = (ViewHolder) holder;
            MpJDTaskOrderInfo info = (MpJDTaskOrderInfo) _data.get(position);
            if (info.getSettingTime().equals("1") || (timeCompare(
                    DateUtils.getDateToString(info.getStartHour().substring(0, info.getStartHour()
                                                                                   .length() - 3)), df.format(new Date())) > 0)) {
                vh.tv_time.setVisibility(View.VISIBLE);
                vh.tv_time.setText(DateUtils.getDateToString(info.getStartHour().substring(0, info.getStartHour()
                                                                                                  .length() - 3)) + "左右");
                vh.tv_taskNum.setVisibility(View.INVISIBLE);
                vh.view1.setBackgroundResource(R.color.list_item_background_pressed);
                vh.view2.setBackgroundResource(R.color.list_item_background_pressed);

            } else {
                vh.view1.setBackgroundResource(R.color.white);
                vh.view2.setBackgroundResource(R.color.white);
                vh.tv_time.setVisibility(View.GONE);
                vh.tv_taskNum.setVisibility(View.VISIBLE);
                if (TextUtils.isEmpty(info.getTaskNumber())) {
                    vh.view1.setVisibility(View.GONE);
                    vh.view.setVisibility(View.VISIBLE);
                    vh.tv_taskId1.setText("ID:" + info.getUserId());
                    vh.tv_taskMoney1.setText(info.getPriceSection() + "元");
                } else {
                    vh.view.setVisibility(View.GONE);
                    vh.view1.setVisibility(View.VISIBLE);
                    vh.tv_taskNum.setText("剩余" + info.getTaskNumber() + "单");
                    vh.tv_taskId.setText("ID:" + info.getUserId());
                    vh.tv_taskMoney.setText(info.getPriceSection() + "元");
                }
            }
            vh.bt_type.setText(info.getBackName());
            vh.tv_goodsType.setText(info.getSingleMulti());

        }

        static class ViewHolder extends RecyclerBaseAdapter.ViewHolder {

            @BindView(R.id.view)
            View view;
            @BindView(R.id.view1)
            View view1;
            @BindView(R.id.view2)
            View view2;
            @BindView(R.id.tv_taskId)
            TextView tv_taskId;
            @BindView(R.id.tv_taskId1)
            TextView tv_taskId1;
            @BindView(R.id.tv_taskMoney)
            TextView tv_taskMoney;
            @BindView(R.id.tv_taskMoney1)
            TextView tv_taskMoney1;
            @BindView(R.id.tv_money)
            TextView tv_money;
            @BindView(R.id.tv_time)
            TextView tv_time;
            @BindView(R.id.bt_type)
            Button bt_type;
            @BindView(R.id.iv_money)
            ImageView iv_money;
            @BindView(R.id.tv_taskNum)
            TextView tv_taskNum;
            @BindView(R.id.tv_goodsType)
            TextView tv_goodsType;

            ViewHolder(int viewType, View view) {
                super(viewType, view);
                ButterKnife.bind(this, view);
            }
        }
    }

    @Override
    protected void requestData(boolean refresh) {
        super.requestData(refresh);
        ApiHttpClient.getTaskInfo(this, "6", new JsonCallback<MpJDTaskOrderInfo>(MpJDTaskOrderInfo.class) {

            @Override
            public void onError(Call call, Exception e) {
                onRequestError();
            }

            @Override
            public void onResponse(ResponseInfo<MpJDTaskOrderInfo> response) {
                int code = response.getCode();
                if (code == 1) {
                    mErrorLayout.setErrorType(EmptyLayout.NETWORK_ERROR);
                    return;
                }
                infoList = response.getData();
                if (infoList == null) {
                    onRequestResponse(infoList);
                } else {
                    for (int i = 0; i < infoList.size(); i++) {
                        if (infoList.get(i).getSettingTime().equals("0")) {
                            mList.add(infoList.get(i));
                        } else {
                            mList1.add(infoList.get(i));
                        }
                    }

                    Collections.sort(mList1, new Comparator<MpJDTaskOrderInfo>() {
                        @Override
                        public int compare(MpJDTaskOrderInfo taskOrderInfo, MpJDTaskOrderInfo t1) {
                            return DateUtils.getDateToString(taskOrderInfo.getStartHour().substring
                                    (0, taskOrderInfo.getStartHour().length())).compareTo(
                                    DateUtils.getDateToString(t1.getStartHour().substring
                                            (0, taskOrderInfo.getStartHour().length())));
                        }
                    });

                    for (int i = 0; i < mList1.size(); i++) {
                        mList.add(mList1.get(i));
                    }
                    onRequestResponse(mList);

                }
            }

            @Override
            public void onAfter() {
                super.onAfter();
                onRequestFinish();
                mList.clear();
            }
        });
    }

    private void selectOver() {
        ApiHttpClient.selectOver(this,
                                 new JsonCallback<String>(String.class,true) {

                                     @Override
                                     public void onBefore(Request request) {
                                         super.onBefore(request);
                                     }

                                     @Override
                                     public void onError(Call call, Exception e) {
                                         toast("网络连接失败，请稍后重试");
                                     }

                                     @Override
                                     public void onResponse(ResponseInfo<String> response) {
                                         int code = response.getCode();
                                         String message = response.getMessage();
                                         if (code == 1) {
                                             showWarnDialog(message);
                                             return;
                                         }
                                         Map<String, Object> _map = response.getFirstEntity();
                                     }

                                     @Override
                                     public void onAfter() {
                                         super.onAfter();
                                     }
                                 }
        );
    }
}
